package com.example.userlogon.service;

import com.example.userlogon.dao.GoodsDao;
import com.example.userlogon.entity.Goods;
import com.example.userlogon.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class GoodsService implements GoodsDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 新增数据的方法
     * @param goods
     * @return
     */
    @Override
    public int add(Goods goods) {
        String sql = "insert into goods values(null,?,?,?,?,?,'0')";
// 1 创建SQL语句
        // 2 调用方法实现
        Object[] args = {goods.getName(), goods.getPrice(), goods.getQuantity(),
        goods.getCategory(),goods.getSupplier()};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int delete(Goods goods) {
        String sql="delete from goods where Id=?";
        Object[] args={goods.getId()};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int update(Goods goods) {

        String sql="update goods set name=?,price=?,quantity=?,category=?,supplier=? where Id=?";
        Object[] args={goods.getName(),goods.getPrice(),goods.getQuantity(),goods.getCategory(),goods.getSupplier(),
                goods.getId()};
        return jdbcTemplate.update(sql, args);
    }

    /***
     *
     * @param goods
     * @return
     */
    @Override
    public Goods findOne(Goods goods) {
        String sql = "select * from goods where Id="+goods.getId().toString();
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Goods>(Goods.class));
    }

    /**
     * 获取所有商品列表的方法
     * @return
     */
    @Override
    public List<Goods> findAll() {
        String sql = "select * from goods";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Goods.class));
    }
}
